<template>
  <div id="login-wrapper" class="flex flex-column h-100">
    <!-- 左上角logo -->
    <div class="sysLogo" />
    <div class="sysName">{{ $config.sysName[$i18n.locale] }}</div>
    <div class="flex align-start justify-between flex-1" style="position: relative">
      <div class="bgMap" />
      <el-card class="box-card">
        <div class="login-title">{{ $t('LOGIN_SYSTEM') }}</div>
        <el-form ref="form" :model="data" :rules="rules" label-width="0px">
          <el-form-item prop="userName" style="margin-bottom: 25px">
            <el-input
              v-model="data.userName"
              prefix-icon="el-icon-user-solid"
              :placeholder="$t('IN_USERNAME')"
              maxlength="32"
            />
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="data.password"
              prefix-icon="el-icon-lock"
              :placeholder="$t('IN_PASSWORD')"
              type="password"
              maxlength="32"
            />
          </el-form-item>
          <el-form-item prop="vcode">
            <div class="flex algin-center">
              <el-input
                v-model="data.vcode"
                prefix-icon="el-icon-key"
                :placeholder="$t('IN_CODE')"
                maxlength="32"
              />
              <div class="ml-10" @click="refreshCode">
                <Identify :identify-code="identifyCode" :content-height="resetSize(40)" />
              </div>
            </div>
          </el-form-item>
          <div class="flex align-center justify-between" style="margin-bottom: 20px">
            <el-checkbox
              v-model="checked"
              style="margin: 0"
              @change="rememberPass"
            >{{ $t('REMEMBER_USERNAME') }}
            </el-checkbox>
            <el-button type="text" class="forgotPwd" @click="forgotPassword">{{
              $t('FORGOT_PASSWORD')
            }}</el-button>
          </div>
          <div class="login-btn">
            <el-button type="primary" style="font-size: 20px" @click="submit">{{
              $t('LOGIN')
            }}</el-button>
          </div>
        </el-form>
      </el-card>
    </div>
    <div class="footer-copy">{{ $config.copyright[$i18n.locale] }}</div>
  </div>
</template>

<script>
  import cryptoJs from 'crypto-js'
  import SystemApi from '@/api/SystemApi'
  import { mapActions, mapGetters } from 'vuex'
  import OperateLogApi from '@/api/system/OperateLogApi.js'
  import Identify from './Identify.vue'

  export default {
    components: { Identify },
    data() {
      const validateCode = (rule, value, callback) => {
        if (!value) {
          callback(new Error(this.$t('IN_CODE')))
        } else if (String(value).toUpperCase() !== this.identifyCode.toUpperCase()) {
          callback(new Error(this.$t('IN_CODE_VALIDATOR')))
        } else {
          callback()
        }
      }
      return {
        checked: false,
        data: {
          userName: '',
          password: '',
          vcode: ''
        },
        identifyCode: '',
        // 验证码规则
        identifyCodes: '123456789ABCDEFGHGKMNPQRSTUVWXYZ',
        rules: {
          userName: [
            {
              required: true,
              message: this.$t('IN_USERNAME'),
              trigger: 'blur'
            }
          ],
          password: [
            {
              required: true,
              message: this.$t('IN_PASSWORD'),
              trigger: 'blur'
            }
          ],
          vcode: [
            {
              required: true,
              validator: validateCode,
              trigger: 'blur'
            }
          ]
        }
      }
    },
    computed: {
      ...mapGetters(['getUser', 'getUserId'])
    },
    created() {
      this.$store.commit('CLEAR_NOTIFY_LIST')
      document.onkeydown = event => {
        var theEvent = window.event || event
        var code = theEvent.keyCode || theEvent.which || theEvent.charCode
        if (code === 13) {
          this.submit()
        }
      }
      const username = localStorage.getItem('userName')
      if (username && username !== 'null') {
        this.checked = true
        this.data.userName = username
      } else {
        localStorage.removeItem('userName')
      }
      console.log(this.$i18n.locale)
    },
    mounted() {
      this.refreshCode()
    },
    methods: {
      ...mapActions(['loadDict', 'loadInfo']),
      // 切换验证码
      refreshCode() {
        this.identifyCode = ''
        this.makeCode(this.identifyCodes, 4)
        console.log(this.identifyCode)
      },
      // 生成随机验证码
      makeCode(o, l) {
        for (let i = 0; i < l; i++) {
          this.identifyCode +=
            this.identifyCodes[Math.floor(Math.random() * (this.identifyCodes.length - 0) + 0)]
        }
      },
      submit() {
        this.$refs.form.validate(valid => {
          if (!valid) {
            if (String(this.data.vcode).toUpperCase() !== this.identifyCode.toUpperCase()) {
              this.refreshCode()
            }
            return false
          }
          if (this.checked === true) {
            localStorage.setItem('userName', this.data.userName)
          } else {
            localStorage.setItem('userName', '')
          }
          this.login()
        })
      },
      login() {
        const pwd = cryptoJs.enc.Utf8.parse(this.data.password)
        const password = cryptoJs.enc.Base64.stringify(pwd)
        const data = {
          username: this.data.userName,
          password: password
        }
        SystemApi.login(data).then(result => {
          if (result) {
            this.updateCookie(result)
            this.loadInfo(true).then(res => {
              // 记录登录日志
              try {
                OperateLogApi.addLog({
                  api: '/authen/login',
                  item: 'LOGIN', // 登录
                  terminal: 'LOGIN', // 登录,
                  realName: this.getUser.realName || '',
                  operateResult: true,
                  object: '/',
                  content: JSON.stringify({
                    userName: this.getUserId,
                    sysName: this.$config.sysName[this.$i18n.locale],
                    i18nKey: 'LOGIN_LOG'
                  })
                })
              } catch (err) {
                console.log(err)
              }
            })
          }
        }).catch(() => {
          this.refreshCode()
        })
      },
      rememberPass() {
        localStorage.setItem('rememberMe', this.checked)
      },
      forgotPassword() {
        this.$notify.error({
          title: this.$t('SYSTEM_TIP'),
          message: this.$t('CONTACT_ADMIN_RESET_PWD'),
          duration: 5000
        })
      },
      updateCookie(result) {
        localStorage.setItem('token', result)
      }
    }
  }
</script>

<style lang="scss">
  #login-wrapper .box-card .el-input__inner {
    height: 40px !important;
    line-height: 38px;
    font-size: 14px;
  }
</style>
